package com.jmx.yp.service.login;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.jmx.yp.dao.IBaseDao;
import com.jmx.yp.entity.GroupEmployee;
import com.jmx.yp.entity.Menus;
import com.jmx.yp.exception.ErrorCode;
import com.jmx.yp.exception.HandlerException;

/**
 * 
 * 功能描述：
 *			ILoginService的接口实现类
 * @author Jenny
 *
 * Date:2011-1-9 下午06:46:39
 */
public class LoginService implements ILoginService {
	
	private IBaseDao dao;
	
	public void setDao(IBaseDao dao){
		this.dao = dao;
	}
	
	/**
	 * 根据登录名及密码验证用户
	 * 	       
	 * @param loginName
	 * @param pass
	 * @return
	 * @throws Exception
	 */
	public GroupEmployee login(String loginName, String pass) throws Exception{
		if(loginName == null || loginName.trim().length() <= 0)
			throw new HandlerException(ErrorCode.LOGINNAME_ERROR);
		
		GroupEmployee employee = (GroupEmployee)dao.getObject("com.jmx.yp.entity.GroupEmployeeMapper.getEmployee", loginName.trim());
		
		if(employee == null)
			throw new HandlerException(ErrorCode.LOGINNAME_ERROR);
		
		//需要加入密码加密
		if(!employee.getGrpemp_pwd().equals(pass))
			throw new HandlerException(ErrorCode.PASSWORD_ERROR);
		
		return employee;
		
	}
	
	/**
	 * 获取菜单
	 * @return
	 * @throws Exception
	 */
	public List getMenu() throws Exception{
		List menuList = (List)dao.getList("com.jmx.yp.entity.MenusMapper.getMenuList", null);
		return getMenuByOrder(menuList);
	}
	
	/**
	 * 按顺序获得菜单列
	 * @param list
	 * @return
	 */
	private List getMenuByOrder(List list){
		if (list == null || list.isEmpty())
			return null;
		
		List uList = new ArrayList();
		for(Iterator its = list.iterator(); its.hasNext();){
			Menus url = (Menus)its.next();
			if(url.getUpmenu() > 0)
				break;
			else{
				uList.add(url);
				recursive(uList, list, url.getSerialid());
			}
		}
		return uList;
	}
	
	/**
	 * 递归查找
	 * @param targetList
	 * @param sourceList
	 * @param id
	 */
	private void recursive(List targetList, List<?> sourceList, Integer id){
		for(Iterator its = sourceList.iterator(); its.hasNext();){
			Menus url = (Menus)its.next();
			if(url.getUpmenu().intValue() == id){
				targetList.add(url);
				recursive(targetList, sourceList, url.getSerialid());
			}
		}
	}
}

